//
//  MeRoomManageController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/10/9.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "MeRoomManageController.h"
#import "MGSwipeTableCell.h"
#import "AddOrEditRoomController.h"
#import "DataManager.h"
#import "MQTTSessionManager.h"
#import "ZTDevice.h"
#import "ZTMovableCellTableView.h"
#import "GlobalConst.h"
#import "UIView+HUD.h"
#import "UIBarButtonItem+Extension.h"

@interface MeRoomManageController ()
<
DataManagerRefreshDelegate,
ZTMovableCellTableViewDataSource,
ZTMovableCellTableViewDelegate,
MGSwipeTableCellDelegate
>
@property (nonatomic, strong, nullable)ZTMovableCellTableView *tableView;
@property (nonatomic, strong)NSMutableArray *rooms;
@end

static NSString *const MeRoomManageCellIdentifier = @"MeRoomManageCellIdentifier";
@implementation MeRoomManageController


#pragma mark - life cycle
- (void)dealloc
{
    debugLogInfo(@"MeRoomManageController dealloc");
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [kDataManager removeRefreshDelegate:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    [self refreshRoomName];
    [kDataManager addRefreshDelegate:self];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshRoomName) name:kZTAddNewRoomNotifKey object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)addRoom {
    
    AddOrEditRoomController *addRoomVc = [[AddOrEditRoomController alloc]initWithType:AddOrEditTypeControllerTypeAdd];
    [self.navigationController pushViewController:addRoomVc animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DataManagerRefreshDelegate

- (void)deviceRefresh:(DataManager *)manager callbackType:(DeviceCallbackType)callbackType
{
    if (callbackType == DeviceCallbackTypeName) {
        [self refreshRoomName];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.rooms.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MGSwipeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:MeRoomManageCellIdentifier];
    if (!cell) {
        cell = [[MGSwipeTableCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:MeRoomManageCellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.rightButtons = [self createRightButtons:2];
        cell.delegate = self;
    }
    cell.textLabel.text = self.rooms[indexPath.row];
    return cell;
}
- (NSArray *)dataSourceArrayInTableView:(ZTMovableCellTableView *)tableView
{
    return self.rooms.copy;
}

- (void)tableView:(ZTMovableCellTableView *)tableView newDataSourceArrayAfterMove:(NSArray *)newDataSourceArray
{
    self.rooms = newDataSourceArray.mutableCopy;
    NSString *roomPath = [MQTTSessionManager roomListPath];
    [NSKeyedArchiver archiveRootObject:self.rooms toFile:roomPath];
    [[NSNotificationCenter defaultCenter]postNotificationName:kZTAddNewRoomNotifKey object:nil];
}

#pragma mark - MGSwipeTableCellDelegate
-(BOOL) swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    debugLogInfo(@"Delegate: button tapped, %@ position, index %d, from Expansion: %@",
          direction == MGSwipeDirectionLeftToRight ? @"left" : @"right", (int)index, fromExpansion ? @"YES" : @"NO");
    
    if (direction == MGSwipeDirectionRightToLeft && index == 0) {
        NSIndexPath * path = [self.tableView indexPathForCell:cell];
        for (ZTDevice *dev in [DataManager sharedManager].deviceListenList) {
            if ([[dev getRoomName] isEqualToString:self.rooms[path.row]]) {
                [self.view yh_showMsgHUD: @"当前房间还有设备不能删除!"];
                return NO;
            }
        }
        if (self.rooms.count <= 1) {
            [self.view yh_showMsgHUD: @"必须得保留一个房间"];
             return NO;
        }
        UIAlertController *alert = [UIAlertController alertControllerWithTitle: @"你确定要删除此房间？"message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        __weak typeof(self)wself = self;
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            __strong typeof(wself)sself= wself;
            if (!sself)
            {
                return;
            }
            //delete button
            NSIndexPath * path = [sself.tableView indexPathForCell:cell];
            NSString *room = sself.rooms[path.row];
            [sself.rooms removeObjectAtIndex:path.row];
            NSString *roomPath  =[MQTTSessionManager roomListPath];
            [NSKeyedArchiver archiveRootObject:sself.rooms toFile:roomPath];
            [sself.tableView reloadData];
            [[NSNotificationCenter defaultCenter]postNotificationName:kZTRemoveRoomNotifKey object:room];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return NO; //Don't autohide to improve delete expansion animation
    }
    else if (direction == MGSwipeDirectionRightToLeft && index == 1)
    {
        AddOrEditRoomController *addRoomVc = [[AddOrEditRoomController alloc]initWithType:AddOrEditTypeControllerTypeEdit];
        [self.navigationController pushViewController:addRoomVc animated:YES];
        return NO;
    }
    
    return YES;
}
-(NSArray *)createRightButtons: (int) number
{
    NSMutableArray * result = [NSMutableArray array];
    UIColor * colors[2] = {RGBColor(239, 75, 58),
        RGBColor(204, 204, 204)};
    UIImage * icons[2] = {[UIImage imageNamed:@"scene_bigdel"], [UIImage imageNamed:@"scene_bigedit"]};
    for (int i = 0; i < number; ++i)
    {
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:@"" icon:icons[i] backgroundColor:colors[i] padding:15 callback:^BOOL(MGSwipeTableCell * sender){
            debugLogInfo(@"Convenience callback received (left).");
            return YES;
        }];
        [result addObject:button];
    }
    return result;
}

#pragma mark - private method
- (void)initSubviews
{
    [self setupNavigationView];
    [self.view addSubview:self.tableView];
    [self layoutPageSubviews];
}
- (void)layoutPageSubviews
{
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}
- (void)setupNavigationView {
    self.navigationItem.title = @"房间管理";
    UIBarButtonItem *addNewRoom = [UIBarButtonItem createBarbuttonItem:@"security_add" target:self action:@selector(addRoom)];
    self.navigationItem.rightBarButtonItem = addNewRoom;
}

- (void)refreshRoomName
{
    NSString *roomPath = [MQTTSessionManager roomListPath];
    self.rooms = [NSKeyedUnarchiver unarchiveObjectWithFile:roomPath];
    __weak typeof(self)wself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        __strong typeof(wself)sself = wself;
        if (!sself) {
            return ;
        }
        [sself.tableView reloadData];
    });
}
#pragma mark - getters and setters
- (ZTMovableCellTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[ZTMovableCellTableView alloc]init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = kBgColor;
        _tableView.sectionHeaderHeight = 0;
        _tableView.sectionFooterHeight = 0;
        _tableView.rowHeight = 55;
        _tableView.tableFooterView = [[UIView alloc]init];
    }
    return _tableView;
}

@end
